const url = new URLSearchParams(window.location.href);
// 请求前缀
const prefix = this.pageObj.getVariables().find(v => v.name === "environmentType")?.value;
let detail = JSON.parse(url && url.get('personDetail') || '{}');

function basePost(url, params) {
    const option = {
        method: 'POST',
        headers: { 'Content-type': 'application/json' },
        body: JSON.stringify(params),
    }
    return fetch(url, option).then(res => res.json())
}

function createParent (data, item) {
    if (!data[item.projectCode]) data[item.projectCode] = {
        title: item.projectName,
        id: `all-${item.projectId || ''}`,
        treeId: `all-${item.projectId || ''}`,
        uniqueKey: `all-${item.projectId || ''}`,
        count: 0,
        children: []
    }

    if (!data[item.projectCode].title) {
        // 处理某条数据没有 title 的情况
        data[item.projectCode].title = item.projectName
    }

    if (data[item.projectCode].id === 'all-') {
        // 处理某条数据没有 projectId 不存在的情况
        data[item.projectCode].id = `all-${item.projectId || ''}`
        data[item.projectCode].treeId = `all-${item.projectId || ''}`
        data[item.projectCode].uniqueKey = `all-${item.projectId || ''}`
    }
}

function extractProject (list, children) {
    const data = {}

    while (list.length) {
        const item = list.shift();
        createParent(data, item)

        if (children) {
            const uniqueKey = `${item.projectCode}-${item.typeName}`;
            item.children = children
            item.count = item.alarmNum
            item.title = item.typeName
            item.id = uniqueKey
            item.treeId = uniqueKey
            item.uniqueKey = uniqueKey

            data[item.projectCode].count += item.alarmNum;
        } else {
            data[item.projectCode].count += 1;
        }

        data[item.projectCode].children.push(item)
        data[item.projectCode].eventList = data[item.projectCode].children
    }

    return Object.values(data)
}

// const whether_process = this.pageObj.getVariables().find(v => v.name === 'whether_process')?.value || 0
basePost(`/${prefix}Event/drillPlanInfo/lastPlan`, { whetherProcess: 0 })
    .then(({ success, result}) => {
        console.log('res', { success, result})
        if(success) {
            const data = extractProject(result)

            console.log('演练列表 - 最新 30 条', data)
            this.widgetObj.setData([{ data: Object.values(data) }])
            this.widgetObj.render()
        }
    }).catch(e => {
    console.error('获取最新', e)
})